package com.nova.android.tvlauncher.ui.fragment.atv

import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.Notification
import com.nova.android.tvlauncher.constants.ConstantsAtv
import com.nova.android.tvlauncher.databinding.FragmentMainAtvBinding
import com.nova.android.tvlauncher.ext.animSlide
import com.nova.android.tvlauncher.ext.bindFragment
import com.nova.android.tvlauncher.ext.findDeviceByPath
import com.nova.android.tvlauncher.ext.getStorageDeviceList
import com.nova.android.tvlauncher.ext.isTFCard
import com.nova.android.tvlauncher.ext.toConfigLocalDto
import com_github_lib_base.base.BaseVMFragment
import com_github_lib_base.base.BaseViewModel
import com_github_lib_base.ext.cache.BaseCache
import com_github_lib_base.ext.dimenValue
import com_github_lib_base.ext.replaceChildFragment
import com_github_lib_base.ext.width
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import observeLiveEvent
import sendLiveEventData
import java.io.File
import kotlin.math.absoluteValue

class MainATVXintuFragment : BaseVMFragment<FragmentMainAtvBinding, BaseViewModel>() {

    // 在类顶部添加动画工具函数
    private fun fadeView(view: View, show: Boolean, duration: Long = 300) {
        view.clearAnimation()
        val animator = if (show) {
            view.alpha = 0f
            view.isVisible = true
            view.animate().alpha(1f).setDuration(duration)
        } else {
            view.animate().alpha(0f).setDuration(duration).withEndAction {
                view.isVisible = false
            }
        }
        animator.start()
    }

    override fun onResume() {
        super.onResume()
        sendLiveEventData(ConstantsAtv.REFRESH_CHANNEL_LIST, true)
    }

    var isFirstFocus = true

    // 将 fragmentMap 提升到类级别，确保只初始化一次
    private val fragmentMap = mapOf(
        0 to HomeAtvXintuFragment::newInstance,
        1 to AppsAtvXintuFragment::newInstance,
    )

    fun showTopView() {
        fadeView(mBind.viewMainTopAtv, true)
        //mBind.viewMainTopAtv.isVisible = true

    }

    fun hideTopView() {
        fadeView(mBind.viewMainTopAtv, false)
        //mBind.viewMainTopAtv.isVisible = false
    }

    private var previousView: View? = null

    override fun initView() {

        readLocalConfig(){
            val isShowVoice = AppCache.configLocalDto?.isShowVoiceIcon != false
            if(!isShowVoice){
                mBind.viewMainTopAtv.mainTopBinding()
                    .viewMainTopLeftAtv.width(com.codeZeng.lib_dimen.R.dimen.qb_px_70.dimenValue())
                mBind.viewMainTopAtv.mainTopBinding()
                    .viewMainTopLeftAtv.mainTopLeftBinding()
                    .tvVoice.isVisible = false
                mBind.viewMainTopAtv.mainTopBinding()
                    .viewMainTopLeftAtv.mainTopLeftBinding()
                    .tvSearch.isVisible = false
                mBind.viewMainTopAtv.mainTopBinding()
                    .viewMainTopLeftAtv.mainTopLeftBinding()
                    .tvKeyboard.isVisible = true
            }

        }

        mBind.apply {
            vp.bindFragment(
                childFragmentManager, arrayListOf(
                    HomeAtvXintuFragment.newInstance(),
                    AppsAtvXintuFragment.newInstance()
                )
            )

            /*vp.setPageTransformer(true){page,position->
                val rlCleanStep: ConstraintLayout? = page.findViewById(R.id.cl_root)
                rlCleanStep?.let {
                    it.alpha = 0f
                    it.animate().alpha(1f).setDuration(800).start()
                }
            }*/





            /*vp.setPageTransformer(true) { page, position ->
                val rlCleanStep: ConstraintLayout? = page.findViewById(R.id.cl_root)
                if (rlCleanStep != null) {
                    when {
                        // 当前页面（接近 position = 0）
                        position >= -1f && position <= 1f -> {
                            // 平滑透明度：根据 position 插值 alpha
                            val alpha = 1f - position.absoluteValue.coerceIn(0f, 1f)
                            rlCleanStep.alpha = 0f // 初始透明
                            rlCleanStep.animate()
                                .alpha(alpha.coerceIn(0f, 1f)) // 动画到目标 alpha
                                .setDuration(800)
                                .setInterpolator(AccelerateDecelerateInterpolator())
                                .start()

                            // 前一页面透明度
                            previousView?.let {
                                if (it != rlCleanStep) {
                                    val prevAlpha = position.absoluteValue.coerceIn(0f, 1f)
                                    it.animate()
                                        .alpha(prevAlpha)
                                        .setDuration(800)
                                        .setInterpolator(AccelerateDecelerateInterpolator())
                                        .start()
                                }
                            }

                            // 更新 previousView
                            previousView = rlCleanStep
                        }
                        // 页面在视野外，设置为完全透明
                        position > 1f -> {
                            rlCleanStep.alpha = 0f
                        }

                        position < -1f -> {
                            rlCleanStep.alpha = 0f
                        }
                    }
                } else {
                    // 视图未准备好，监听布局完成
                    page.viewTreeObserver.addOnGlobalLayoutListener(object :
                        ViewTreeObserver.OnGlobalLayoutListener {
                        override fun onGlobalLayout() {
                            page.findViewById<ConstraintLayout>(R.id.cl_root)?.let {
                                if (position >= -1f && position <= 1f) {
                                    val alpha = 1f - position.absoluteValue.coerceIn(0f, 1f)
                                    it.alpha = 0f
                                    it.animate()
                                        .alpha(alpha.coerceIn(0f, 1f))
                                        .setDuration(800)
                                        .setInterpolator(AccelerateDecelerateInterpolator())
                                        .start()

                                    previousView?.let { prev ->
                                        if (prev != it) {
                                            val prevAlpha = position.absoluteValue.coerceIn(0f, 1f)
                                            prev.animate()
                                                .alpha(prevAlpha)
                                                .setDuration(800)
                                                .setInterpolator(AccelerateDecelerateInterpolator())
                                                .start()
                                        }
                                    }
                                    previousView = it
                                } else if (position > 1f || position < -1f) {
                                    it.alpha = 0f
                                }
                            }
                            page.viewTreeObserver.removeOnGlobalLayoutListener(this)
                        }
                    })
                }
            }*/

        }
        mBind.viewMainTopAtv.onTabSelected {
            delayLoadFragment(it)
        }

        initNotification()
        observeLiveEvent<Pair<Boolean, String>>(ConstantsAtv.IS_INSERT_STORAGE) {
            handleStorageChange(it)
        }
    }

    private fun readLocalConfig(callback: (() -> Unit)? = null) {
        val jsonFile = File("vendor/etc/config.json")
        try {
            val configLocal = jsonFile.toConfigLocalDto()


            AppCache.configLocalDto = configLocal
            configLocal.filterApps?.toMutableList()?.let {
                BaseCache.filterAppsList = it
            }

            callback?.invoke()
        } catch (e: Exception) {
            callback?.invoke()
        }
    }


    private fun initNotification() {
        //加载通知
        val storageList = requireActivity().getStorageDeviceList()
        AppCache.notificationList = storageList.toMutableList()
        mBind.viewMainTopAtv.mainTopBinding().viewMainTopRightAtv.mainTopRightBinding().tvNotification.setNotificationText(
            storageList.size.toString()
        )

    }

    fun setVoiceFocus(isFocus: Boolean) {
        mBind.viewMainTopAtv.setVoiceFocus(isFocus)
    }

    private var loadFragmentJob: Job? = null
    private var delayTime: Long = 500L // 延迟时间，300ms 可以根据需求调整
    private fun delayLoadFragment(index: Int) {
        // 清除上一次的 Fragment 加载任务
        loadFragmentJob?.cancel()
        // 启动一个新的延迟任务来加载 Fragment
        loadFragmentJob = lifecycleScope.launch {
            delay(delayTime)
            mBind.vp.setCurrentItem(index, false)
            //loadFragment(index)
        }

    }

    private fun loadFragment(index: Int) {

        val fragmentCreator = fragmentMap[index]

        // 如果 fragmentCreator 不为空，则提交 Fragment
        fragmentCreator?.let {
            commit(it.invoke())
        }
    }

    private fun commit(fragment: Fragment) {
        if (!fragment.isAdded) {
            replaceChildFragment(
                fragment,
                R.id.fl_container
            )
        }
    }


    private fun handleStorageChange(it: Pair<Boolean, String>) {
        val (isInsert, path) = it
        val deviceName = path.isTFCard().second

        val localList =
            AppCache.notificationList as MutableList<Notification.StorageDevice>


        val isContain = localList.any {
            path.contains(it.path)
        }
        if (!isContain) {
            val bean = path.findDeviceByPath()
            if (bean != null) {
                if (isInsert) {
                    localList.add(0, bean)
                }
            }
        } else {
            for (i in localList.size - 1 downTo 0) {
                if (path.contains(localList[i].path)) {
                    localList.removeAt(i)
                }
            }
        }


        mBind.viewMainTopAtv.mainTopBinding().viewMainTopRightAtv.mainTopRightBinding().tvNotification.setNotificationText(
            localList.size.toString()
        )
        AppCache.notificationList = localList
        sendLiveEventData(ConstantsAtv.UPDATE_STORE_DEVICE_LIST, true)
        if (isInsert) {
            //插入外部设备
            mBind.tvStorageTip.text = deviceName
            if (mBind.tvStorageTip.text.isNotEmpty()) mBind.rlSlide.animSlide()
        } else {
            //拔出外部设备
        }
    }


    companion object {
        @JvmStatic
        fun newInstance() =
            MainATVXintuFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }

}


